import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

interface ListState {
  loading: boolean;
  list: ListItemState[];
}

interface ListItemState {
  id: string;
  title: string;
  tel: string;
  name: string;
  sex: string;
  address: string;
}

const initialState: ListState = {
  loading: true,
  list: [],
};

export const fetchList = createAsyncThunk("list/fetchList", async () => {
  const resp = await axios.get("/api/list");
  return resp.data;
});

export const deleteList = createAsyncThunk(
  "list/deleteList",
  async (id: string, ThunkApi) => {
    // 删除请求
    const resp = await axios.delete("/api/list/" + id);
    // 重新请求列表
    ThunkApi.dispatch(fetchList());
    return resp.data;
  }
);

export const addList = createAsyncThunk(
  "list/addList",
  async (data: {
		title: string;
		tel: string;
		name: string;
		sex: string;
		address: string;
	}, ThunkApi) => {
    // 添加请求
    const resp = await axios.post("/api/list", data);
    // 重新请求列表
    return resp.data;
  }
);

export const editList = createAsyncThunk(
  "list/editList",
  async (data: ListItemState, ThunkApi) => {
    // 修改请求
    const resp = await axios.post("/api/list/" + data.id, data);
    // 重新请求列表
    ThunkApi.dispatch(fetchList());
    return resp.data;
  }
);


const listSlice = createSlice({
  name: "list",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchList.pending.type](state) {
      state.loading = true;
    },
    [fetchList.fulfilled.type](state, action) {
      state.loading = false;
      state.list = action.payload.data;
    },
  },
  // extraReducers(builder) {
  // 	// builder.addCase
  // }
});

export default listSlice;
